//
//  ZLMainViewController.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/15.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import UIKit
import SVProgressHUD

///主控制器
class ZLMainViewController: UITabBarController {

    lazy var composeButton: UIButton = UIButton.hm_button(withImageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button", highlightSuffix: "")
    //定时器
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupChildControllers()
        
        setupComposeButton()
        
        setUpTimer()
        
        //设置新特性
        setupNewFeatrue()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: ZLUersShouldLoginNotigication), object: nil)
    
    }
    deinit {
        
        //释放定时器
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc fileprivate func userLogin(n: Notification){
        
        print("登录通知")
        var when = DispatchTime.now()
        //判断n.object是否有值，如果有值提示用户重新登录
        
        if (n.object != nil)
        {
            //设置指示器样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录超时，请重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现微博登录控制器
            let vc = ZLOuthorViewController()
            let navi = UINavigationController(rootViewController: vc)
            self.present(navi, animated: true, completion: nil)
        }
        
        
        
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return .portrait
    }
    //保证方法私有 仅在当前类中访问
    //@objc 允许这个函数运行时 OC 的消息机制被调用
    @objc fileprivate func composeStatus() {
        
        print("撰写微博")
        
        //是否登录
        
        //实例视图
        let v = ZLComposeTypeView.composeType()
        
        
        //显示图示
        v.show {[weak v] (clsName) in
            
            guard let clsName = clsName, let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
                
                return
            }
            // 46-关于图片清晰度的处理，替换 wap360
            let vc = cls.init()
            
            let navi = UINavigationController(rootViewController: vc)
            
            //导航控制器强行更新约束
            //提示： 开发中如果法案不希望的布局约束和红花混在一起，应该向前寻找，更新约束
            navi.view.layoutIfNeeded()
            
            self.present(navi, animated: true, completion: {
                //循环引用
                v?.removeFromSuperview()
            })
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}
// MAR ---设置新特性的视图
extension ZLMainViewController{
    
    fileprivate func setupNewFeatrue(){
        
        //判断是否登录
        if !ZLNetWorkManager.shared.userLogon{
            
            return
        }
        //如果更新 显示新特性，否则显示欢迎界面
        let v = isnewVersion ? ZLNewFeatureView.newFeatrue() : ZLWelcomeView.welcomeView()
        
        
        //添加视图
        view.addSubview(v)
    }
    
    //检查新版本
    private var isnewVersion: Bool{
        //去当前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        //保存在document 目录中的之前的版本号
        let path: String = ("version" as NSString).hm_appendDocumentDir!
        let boxversion = (try? String(contentsOfFile: path)) ?? ""
        
        //比较版本号
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //比较结果  是否一致
        
        return currentVersion != boxversion
        //return true
    }
}
///MARK -- UITabBarControllerDelegate
extension ZLMainViewController: UITabBarControllerDelegate{
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let index = (childViewControllers as NSArray).index(of: viewController)
        //重复点击了首页按钮
        if selectedIndex == 0 && index == selectedIndex
        {
            //表格滚动底部
            let navi = childViewControllers[0] as! UINavigationController
            
            let vc = navi.childViewControllers[0] as! ZLBaseViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            //刷新表格
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                
                vc.loadData()
                
            })
            //清除tableBarItem的badgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        
        
        
        //判断目标控制是不是Viewcontroller
        
        return !viewController.isMember(of: UIViewController.classForCoder())
        
    }
    
}
///MARK --定时器相关方法
extension ZLMainViewController{
    
    fileprivate func setUpTimer(){
        
        //时间建议长一些
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    @objc private func updateTimer(){
        
        if !ZLNetWorkManager.shared.userLogon{
            
            return
        }
        //测试未读数量
        ZLNetWorkManager.shared.unReadCount { (count) in
            
            //设置首页tabBar数量
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            //设置APPbadagenum 从iOS8.0之后用户授权才可以显示
            UIApplication.shared.applicationIconBadgeNumber = count
            
            print(count)
        }
    }
}
//extension类似OC中的分类  在swift中可以用来切分代码块
//可以吧相近功能的函数放在一个extensio中
//便于代码维护
//注意 和OC的分类一样extension中不能定义属性

extension ZLMainViewController {
    
    @objc fileprivate func setupComposeButton() {
        
        
        tabBar.addSubview(composeButton)
        
        //计算按钮的位置
        let count: CGFloat = CGFloat(childViewControllers.count)
        //将宽度减少  按钮的宽度变大
        let w = tabBar.bounds.width / count
        //OC CGRectInset 正数向内缩进 负数效果外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }

    //这是所有自控制器
    @objc fileprivate func setupChildControllers() {
        //获取沙河的json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        //判断data是否有内容
        if data == nil
        {
            let path = Bundle.main.path(forResource: "Demo.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        //data一定会有内容
        //从bundle加载配置json
        //try？跑出异常 如果解析成功就有值 否则为nil
        //try! 强烈不推荐  ，如果解析成功就有值，否则崩溃
        //处理异常 try 
        /*
         do{
         
         }
         catch{
         
         print(error)
         }
         */
        
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String: AnyObject]] else{
            
            return
        }
        
        //现在很多引用程序中，界面的创建依赖网络的json
        /*let array = [
            ["clsName": "ZLHomeViewController","title": "首页","imageName": "home","visitorInfo": ["imageName": "","message": "关注一些人,回这里看看有什么惊喜"]],
            ["clsName": "ZLMessageViewController","title": "消息","imageName": "message_center","visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
            ["clsName": "UIViewController"],
            ["clsName": "ZLDiscoverViewController","title": "发现","imageName": "discover","visitorInfo": ["imageName": "visitordiscover_image_message","message": "登录后，最新、最热微博尽在掌握，不会再与事实潮流擦肩而过"]],
            ["clsName": "ZLProfileViewController","title": "我的","imageName": "profile","visitorInfo": ["imageName": "visitordiscover_image_profile","message": "登录后，你的微博、相册、个人信息会显示在这里，展示给别人"]],
            
        ]*/
        //测试数据格式转换是否正确
        //(array as NSArray).write(toFile: "/Users/hanju001/Desktop/Demo.plist", atomically: true)
        //let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        
        //(data as NSData).write(toFile: "/Users/hanju001/Desktop/Demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        
        for dic in array!
        {
            arrayM.append(controllerDic(dic: dic as [String : AnyObject]))
        }
        
        viewControllers = arrayM
        
        
    }
    //使用字典创建爱你一个自控制器
    private func controllerDic(dic: [String: AnyObject]) -> UIViewController {
        
        guard let clsName = dic["clsName"],let title = dic["title"],let imageName = dic["imageName"],let cls = NSClassFromString(Bundle.main.namespace + "." + (clsName as! String)) as? ZLBaseViewController.Type,let visitorDic = dic["visitorInfo"] else {
            
            
            return UIViewController()
            
        }
        
        let vc = cls.init()
        vc.title = title as? String;
        
        //设置访客信息的字典
        vc.visitorInfoDictionary = visitorDic as? [String : String]
        vc.tabBarItem.image = UIImage(named: "tabbar_" + (imageName as! String))
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + (imageName as! String) + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .highlighted)
        //系统默认的是12号 设置高亮不起作用
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
    
        //设置tabBar的标题
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        
        let navi = ZLNavigationViewController(rootViewController: vc)
        return navi
        
    }
    
}
